package itbour.onetouchshow.activity.challengezone.filter;

import android.animation.ValueAnimator;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.xiao.nicevideoplayer.EditNiceVideoPlayer;
import com.xiao.nicevideoplayer.LogUtil;

import java.text.DecimalFormat;

import butterknife.BindView;
import itbour.onetouchshow.R;
import itbour.onetouchshow.activity.version1_2.CutVideoActivity;
import itbour.onetouchshow.activity.version1_2.CutVideoContract;
import itbour.onetouchshow.utils.AssetsDataUtils;
import itbour.onetouchshow.utils.DateUtils;
import itbour.onetouchshow.utils.FileUtils;
import itbour.onetouchshow.utils.L_;
import itbour.onetouchshow.utils.T_;
import itbour.onetouchshow.utils.TypeCastHelper;
import itbour.onetouchshow.utils.UIUtils;
import itbour.onetouchshow.utils.video.EditPlayVideoFrames;
import itbour.onetouchshow.widget.RangeSeekBar;

/**
 * Created by Administrator on 2018/1/23.
 */

public class CutEidtVideoActivity extends CutVideoActivity implements CutVideoContract.View {

    @BindView(R.id.id_seekBarLayout)
    protected LinearLayout seekBarLayout;
    @BindView(R.id.positionIcon)
    protected ImageView positionIcon;
    /**
     * 裁剪基础框的宽度
     */
    protected double mscaleWidth = UIUtils.WH()[0] * 0.9;
    protected double mfoodViewWidth = UIUtils.WH()[0] * 0.1;
    /**
     * 默认itme宽度
     */
    // protected int mItemWidth = UIUtils.WHD()[0] / 4;
    /**
     * 左边距
     */
    protected int leftMargen = UIUtils.dp2px(10);
    RangeSeekBar seekBar;
    private long leftProgress, rightProgress;
    private long scrollPos = 0;
    private boolean isSeeking;
    private float averagePxMs;//每px所占用的ms毫秒
    private ValueAnimator animator;
    private Handler handler = new Handler();
    private Runnable run = new Runnable() {
        @Override
        public void run() {
            videoProgressUpdate();
            handler.postDelayed(run, 1000);
        }
    };
    private final RangeSeekBar.OnRangeSeekBarChangeListener mOnRangeSeekBarChangeListener = new RangeSeekBar.OnRangeSeekBarChangeListener() {
        @Override
        public void onRangeSeekBarValuesChanged(RangeSeekBar bar, long minValue, long maxValue, int action, boolean isMin, RangeSeekBar.Thumb pressedThumb) {
            L_.e("-----minValue----->>>>>>" + minValue);
            L_.e("-----maxValue----->>>>>>" + maxValue);
            leftProgress = minValue + scrollPos;
            rightProgress = maxValue + scrollPos;
            L_.e("-----leftProgress----->>>>>>" + leftProgress);
            L_.e("-----rightProgress----->>>>>>" + rightProgress);
            switch (action) {
                case MotionEvent.ACTION_DOWN:
                    isSeeking = false;
                    break;
                case MotionEvent.ACTION_MOVE:
                    isSeeking = true;
                    landLayoutVideo.seekTo(pressedThumb == RangeSeekBar.Thumb.MIN ?
                            leftProgress : rightProgress);
                    cancleSeekingView();
                    break;
                case MotionEvent.ACTION_UP:
                    isSeeking = false;
                    //从minValue开始播
                    landLayoutVideo.seekTo(leftProgress);
                    break;
                default:
                    break;
            }
            L_.e("seekBar leftProgress  :" + leftProgress);
            L_.e("seekBar rightProgress  :" + rightProgress);
            if (rightProgress > mDuration) {
                startTime = mDuration - MIN_CUT_DURATION;
                tvStart.setText(startTime / 100 * 1.0 / 10 + "s");
                tvEnd.setText(mDuration / 100 * 1.0 / 10 + "s");
            } else {
                DecimalFormat df = new DecimalFormat("#.#");
                double end = rightProgress / 100 * 1.0 / 10;
                String endTimeTv = df.format(end);
                double start = leftProgress / 100 * 1.0 / 10;
                String startTimeTv = df.format(start);
                tvStart.setText(startTimeTv + "s");
                tvEnd.setText(endTimeTv + "s");
            }
            onChageUrlStartPlay(videoUrl, leftProgress, rightProgress);
            startSeekingView();
        }
    };


    @Override
    public void cliptAndSave() {
        String newVideoPath = FileUtils.getDownloadDir() + DateUtils.getYMD() + FileUtils.getMP4FileName(videoUrl);
        showProgressDialogWithText("视频剪辑中...");
        //  leftProgress = seekBar.getSelectedMinValue() + scrollPos;
        //  rightProgress = seekBar.getSelectedMaxValue() + scrollPos;
        if (rightProgress < leftProgress) {
            T_.showToastReal("请调整时间");
            return;
        } else {
            MIN_CUT_DURATION = TypeCastHelper.toInt(rightProgress) - TypeCastHelper.toInt(leftProgress);
        }
        if (EditPlayVideoFrames.startclipDecodeVideo(videoUrl, newVideoPath, leftProgress, MIN_CUT_DURATION)) {
            dismissProgressDialog();
            T_.showCustomToast("剪切成功" + newVideoPath);
            Intent intent = new Intent();
            intent.putExtra("videoUrl", newVideoPath);
            setResult(8000, intent);
            finish();
        } else {
            T_.showCustomToast("保存失败，请稍后再试");
            dismissProgressDialog();
        }
    }


    public void cancleSeekingView() {
        handler.removeCallbacks(run);
        if (positionIcon.getVisibility() == View.VISIBLE) {
            positionIcon.setVisibility(View.GONE);
        }
        positionIcon.clearAnimation();
        if (animator != null && animator.isRunning()) {
            animator.cancel();
        }
    }


    public void startSeekingView() {
        positionIcon.clearAnimation();
        if (animator != null && animator.isRunning()) {
            animator.cancel();
        }
        anim();
        handler.removeCallbacks(run);
        handler.post(run);
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_edit_video;
    }


    @Override
    public long setMinDuration() {
        return 10000;
    }


    /**
     * 设置布局位置  以及计算RecycleviewItem的宽度
     */
    @Override
    protected void calculateViewLayout() {
        MIN_CUT_DURATION = setMinDuration();
        idRyRoot.setVisibility(View.GONE);
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) igSeletor.getLayoutParams();
        igSeletor.setScaleType(ImageView.ScaleType.FIT_XY);
        //避免抽帧超出
        layoutParams.width = (int) mscaleWidth + UIUtils.dp2px(2);
        layoutParams.leftMargin = leftMargen - UIUtils.dp2px(1);

        RelativeLayout.LayoutParams layoutParams2 = (RelativeLayout.LayoutParams) idRyCount.getLayoutParams();
        layoutParams2.width = (int) mscaleWidth;
        layoutParams2.leftMargin = leftMargen;

        String s = AssetsDataUtils.videoWHDA(videoUrl)[2];
        int duration = (int) (Double.valueOf(s) * 1000);
        // initEditVideo(Long.valueOf(String.valueOf(duration)));
        mDuration = duration;
        //分成是N等分
        MAX_COUNT_RANGE = Integer.valueOf(String.valueOf(mDuration / 1000));
        if (mDuration < MIN_CUT_DURATION) {
            MIN_CUT_DURATION = mDuration;
        }
        //取整
        DecimalFormat df = new DecimalFormat("#.#");
        double end = MIN_CUT_DURATION / 1000;
        String endTimeTv = df.format(end);
        tvEnd.setText(endTimeTv + "s");
        float scale = MIN_CUT_DURATION * 1.0f / duration;
        //减去左边的间距
        maxWidth = mscaleWidth / scale;
        averageMsPx = (float) (duration / maxWidth);


        //重新设置ItmeWidth
        mItemWidth = (int) Math.ceil(maxWidth / MAX_COUNT_RANGE);


        //init seekBar
        leftProgress = 0;
        rightProgress = MIN_CUT_DURATION;
        seekBar = new RangeSeekBar(this, 0L, MIN_CUT_DURATION);
        seekBar.setSelectedMinValue(0L);
        seekBar.setSelectedMaxValue(MIN_CUT_DURATION);
        seekBar.setMin_cut_time(2000);//设置最小裁剪时间
        seekBar.setNotifyWhileDragging(true);
        seekBar.setOnRangeSeekBarChangeListener(mOnRangeSeekBarChangeListener);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((int) mscaleWidth + UIUtils.dp2px(2), LinearLayout.LayoutParams.MATCH_PARENT);
        params.leftMargin = leftMargen;
        seekBarLayout.addView(seekBar, params);
        averagePxMs = (float) (mscaleWidth * 1.0f / (rightProgress - leftProgress));


        positionIcon.clearAnimation();
        if (animator != null && animator.isRunning()) {
            animator.cancel();
        }
        anim();
        handler.removeCallbacks(run);
        handler.post(run);


    }

    @Override
    protected View getFootView() {
        View footview = UIUtils.inflate(R.layout.video_item_place);
        TextView textView = footview.findViewById(R.id.id_ry_place);
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) textView.getLayoutParams();
        layoutParams.width = (int) mfoodViewWidth - leftMargen;
        // layoutParams.height = (int) (UIUtils.WH()[0] / 0.44);
        textView.setLayoutParams(layoutParams);
        LogUtil.i(" layoutParams1.width" + layoutParams.width);
        return footview;
    }

    @Override
    protected View getHeadView() {
        View footview = UIUtils.inflate(R.layout.video_item_place);
        TextView textView = footview.findViewById(R.id.id_ry_place);
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) textView.getLayoutParams();
        layoutParams.width = leftMargen;
        textView.setLayoutParams(layoutParams);
        LogUtil.i(" layoutParams1.width" + layoutParams.width);
        return footview;
    }


    @Override
    protected RecyclerView.OnScrollListener setOnRecyclviewSollerListener() {
        OnRecyclviewSollerListener onRecyclviewSollerListener = new OnRecyclviewSollerListener();
        return onRecyclviewSollerListener;
    }

    @Override
    protected void onChageUrlStartPlay(String viudeUrl, long startTime, long endTime) {
        if (!TextUtils.isEmpty(viudeUrl)) {
            MIN_CUT_DURATION = rightProgress - leftProgress;
            landLayoutVideo.setmDuration(MIN_CUT_DURATION);
            landLayoutVideo.setchageUrlUp(viudeUrl, startTime, endTime, MIN_CUT_DURATION);
        }
    }

    private void anim() {
        if (positionIcon.getVisibility() == View.GONE) {
            positionIcon.setVisibility(View.VISIBLE);
        }
        final RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) positionIcon.getLayoutParams();
        L_.e("params.leftMargin  leftProgress:" + leftProgress);
        L_.e("params.leftMargin  rightProgress:" + rightProgress);
        int start = (int) (leftMargen + (leftProgress - scrollPos) * averagePxMs);
        int end = (int) (leftMargen + (rightProgress - scrollPos) * averagePxMs);
        L_.e("params.leftMargin  start:" + start);
        L_.e("params.leftMargin  end:" + end);
        animator = ValueAnimator.ofInt(start, end)
                .setDuration((rightProgress - scrollPos) - (leftProgress - scrollPos));
        L_.e("params.leftMargin  setDuration:" + (rightProgress - leftProgress));
        animator.setInterpolator(new LinearInterpolator());
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                if (params == null) return;
                params.leftMargin = (int) animation.getAnimatedValue();
                L_.e("params.leftMargin:" + params.leftMargin);
                if (positionIcon == null) {
                    return;
                }
                //  tvStart.setLayoutParams(params);
                positionIcon.setLayoutParams(params);
            }
        });
        animator.start();
        landLayoutVideo.setMediaPlayerOnCompletionListener(new EditNiceVideoPlayer.MediaPlayerOnCompletionListener() {
            @Override
            public void onCompletion() {
                //T_.showCustomToast("重播");
                // long currentPosition = landLayoutVideo.getCurrentPosition();
                onChageUrlStartPlay(videoUrl, leftProgress, rightProgress);
                startSeekingView();
            }
        });
    }

    private void videoProgressUpdate() {
        if (landLayoutVideo == null) {
            handler.removeCallbacks(run);
            return;
        }
        long currentPosition = landLayoutVideo.getCurrentPosition() + 800;
        L_.e("params currentPosition:" + currentPosition);
        L_.e("params rightProgress:" + rightProgress);
        L_.e("params leftProgress:" + leftProgress);
        if (currentPosition >= rightProgress) {
            onChageUrlStartPlay(videoUrl, leftProgress, rightProgress);
            positionIcon.clearAnimation();
            if (animator != null && animator.isRunning()) {
                animator.cancel();
            }
            anim();
        }
    }


    @Override
    protected void onStartPlay(String viudeUrl, String videoName) {
        if (!TextUtils.isEmpty(viudeUrl)) {
            landLayoutVideo.setUp(viudeUrl, null);
        }
        if (!TextUtils.isEmpty(videoName)) {
            controller.setTitle(videoName);
        }

    }

    public String getTime(long curPostion) {
        DecimalFormat df = new DecimalFormat("#.#");
        double time = curPostion / 1000;
        return df.format(time) + "s";
    }

    public class OnRecyclviewSollerListener extends RecyclerView.OnScrollListener {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if (MIN_CUT_DURATION >= mDuration) {
                return;
            }
            if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                isSeeking = false;
                if (landLayoutVideo != null)
                    landLayoutVideo.restart();
            } else {
                isSeeking = true;
                if (landLayoutVideo != null)
                    landLayoutVideo.pause();
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            isSeeking = false;
            if (MIN_CUT_DURATION >= mDuration) {
                return;
            }
            cancleSeekingView();
            scrollX = getScrollXDistance();
            double startscrollPos = averageMsPx * scrollX;
            landLayoutVideo.seekTo((long) startscrollPos);
            double endscrollPos = averageMsPx * (scrollX + mscaleWidth);
            startTime = TypeCastHelper.toLong(startscrollPos);
            long endTime = TypeCastHelper.toLong(endscrollPos);

            DecimalFormat df = new DecimalFormat("#.#");
            double end = endscrollPos / 1000;
            String endTimeTv = df.format(end);
            double start = startscrollPos / 1000;
            String startTimeTv = df.format(start);

            if (endTime > mDuration) {
                startTime = mDuration - MIN_CUT_DURATION;
                tvStart.setText(getTime(startTime));
                tvEnd.setText(getTime(mDuration));
            } else {
                tvStart.setText(startTimeTv + "s");
                tvEnd.setText(endTimeTv + "s");
            }
            isSeeking = false;
            scrollPos = (long) startscrollPos;
            leftProgress = seekBar.getSelectedMinValue() + scrollPos;
            rightProgress = seekBar.getSelectedMaxValue() + scrollPos;
            L_.e("seekBar leftProgress  :" + leftProgress);
            L_.e("seekBar rightProgress  :" + rightProgress);
            onChageUrlStartPlay(videoUrl, leftProgress, rightProgress);
            startSeekingView();
            // lastScrollX = scrollX;
        }
    }

}